package com.tange.module.qrcode.scan;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.base.BaseActivity;
import com.tange.base.toolkit.StatusNavUtils;
import com.tange.base.toolkit.StringUtils;
import com.tange.module.qrcode.biz.R;
import com.tg.appcommon.android.DeviceAddSoundConstants;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.MediaPlayerHelper;
import com.tg.appcommon.android.PermissionUtil;
import com.tg.appcommon.android.SoundPlayerManager;
import com.tg.appcommon.android.TGLog;

import java.util.List;

/**
 * 二维码扫码页，只负责扫描二维码，并将扫描结果回调出去。
 *
 *
 *
 *
 *
 *
 *
 *
 *    =====================================
 *
 *
 *
 *
 *     注意：不要在这里加业务逻辑 ！！！！！
 *
 *
 *
 *    =====================================
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */
public class QrcodeScanActivity extends BaseActivity implements OnQrCodeScanListener {

    private static final int PERMISSION_REQUEST_CODE = 9898;

    private static final String TAG = "QrcodeScanActivity";

    private ImageButton backButton;

    private final static String[] needQrcodeScanPermissions = {
            Manifest.permission.CAMERA
    };


    private final MediaPlayerHelper mediaPlayerHelper = new MediaPlayerHelper();

    private final Handler uiHandler = new Handler(Looper.getMainLooper());

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    public static void launch(Activity activity) {
        activity.startActivityForResult(new Intent(activity, QrcodeScanActivity.class), QrCodeScanConstants.QRCODE_SCAN_REQUEST_CODE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        setContentView(R.layout.module_qrcode_activity_qrcode_scan);
        hideActionBar();

        if (savedInstanceState == null) {
            QrcodeScanFragment scanQrcodeFragment = QrcodeScanFragment.newInstance();
            scanQrcodeFragment.setOnQrCodeScanListener(this);
            getSupportFragmentManager().beginTransaction().add(R.id.fl_lan_add_container, scanQrcodeFragment, "scanQrcodeFragment").commit();
        }

        initView();
    }

    public ImageButton getBackButton() {
        return backButton;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(RESULT_CANCELED);
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        String language = LanguageUtils.getLanguage(this);
        if (StringUtils.equals(language, LanguageUtils.LANGUAGE_VI)) {
            playSound();
        }
    }

    private void playSound() {
        uiHandler.postDelayed(() -> {
            mediaPlayerHelper.playAssetsSound("scan.mp3");
        }, 1000);
    }


    @Override
    protected void onPause() {
        super.onPause();
        pauseSound();
    }

    private void pauseSound() {
        uiHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void initView() {

        int statusBarHeight = (int) getResources().getDimension(R.dimen.status_bar_height);
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }

        backButton = findViewById(R.id.back_toolbar_btn);
        backButton.setOnClickListener(view -> {
            setResult(RESULT_CANCELED);
            finish();
        });

        requestPermission();

        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) backButton.getLayoutParams();
        lp.topMargin = statusBarHeight;
        backButton.setLayoutParams(lp);
    }


    public void setToolbar(@DrawableRes int resId, String title) {
        StatusNavUtils.setTranslucentStatus(this);
        if (backButton != null){
            backButton.setImageResource(resId);
        }
    }

    private Fragment getVisibleFragment() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for(Fragment fragment:fragments) {
            if(fragment != null && fragment.isVisible())
                return fragment;
        }
        return null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] paramArrayOfInt) {
        super.onRequestPermissionsResult(requestCode, permissions, paramArrayOfInt);
        TGLog.d(TAG, "onRequestPermissionsResult===");
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (!PermissionUtil.verifyPermissions(paramArrayOfInt)) {      //没有授权
                TGLog.d(TAG, "onRequestPermissionsResult = false");

                remindCameraPermission();

            } else {
                TGLog.d(TAG, "onRequestPermissionsResult = true");
            }
            Fragment fragment = getVisibleFragment();
            if (fragment instanceof QrcodeScanFragment) {
                QrcodeScanFragment scanQrcodeFragment = QrcodeScanFragment.newInstance();
                scanQrcodeFragment.setOnQrCodeScanListener(this);
                getSupportFragmentManager().beginTransaction().add(R.id.fl_lan_add_container, scanQrcodeFragment, "scanQrcodeFragment").commitAllowingStateLoss();
            }
        }
    }

    private void remindCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            String title =  getString(com.module.appcommon.R.string.no_permission_to_work_with_qrcode);
            String content =  getString(com.module.appcommon.R.string.enable_permission_camera);
            PermissionUtil permissionUtil = new PermissionUtil(this);
            permissionUtil.showSettingAlertDialog(title, content, getString(com.module.appcommon.R.string.permission_settings), getString(com.module.appcommon.R.string.cancel), () -> {

            });
        }
    }

    private void requestPermission() {
        PermissionUtil permissionUtil = new PermissionUtil(QrcodeScanActivity.this);
        permissionUtil.checkPermissions(QrcodeScanActivity.this, PERMISSION_REQUEST_CODE, QrcodeScanActivity.needQrcodeScanPermissions);
    }

    @Override
    public void onSuccess(String qrCodeContent) {
        Intent ret = new Intent();
        ret.putExtra(QrCodeScanConstants.QRCODE_SCAN_CONTENT, qrCodeContent);
        setResult(RESULT_OK, ret);
        finish();
    }
}
